package com.mobile.web.config;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;

	public class crosFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) {

	}
	@Override
	public void destroy() {

	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
	                     FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest request = (HttpServletRequest) req;
	    HttpServletResponse response = (HttpServletResponse) resp;
		//加入多个跨域端口
		String []  allowDomain= {"http://192.168.5.151:21915"};
		Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
		String originHeader=((HttpServletRequest) req).getHeader("Origin");
	    response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
	    response.setHeader("Access-Control-Allow-Origin",originHeader);
	    response.setHeader("Access-Control-Max-Age", "0");
	    response.setHeader("Access-Control-Allow-Credentials", "true");
	    response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
	    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

	    if ("OPTIONS".equals(request.getMethod())) {
	        response.setStatus(HttpStatus.NO_CONTENT.value());
	        return;
	    } else {
	        chain.doFilter(request, response);
	    }
	}
}
